import Vue from "vue";
const Bus = new Vue();

/**
 * 判断、获取页面可见性属性支持的属性名称
 */
const getHiddenProp = () => {
  var prefixes = ["webkit", "moz", "ms", "o"];
  if ("hidden" in document) {
    return "hidden";
  }
  for (var i = 0; i < prefixes.length; i++) {
    if (prefixes[i] + "Hidden" in document) {
      return prefixes[i] + "Hidden";
    }
  }
  return null;
};

/**
 * 获取页面可见性状态属性名称
 */
const getVisibilityState = () => {
  var prefixes = ["webkit", "moz", "ms", "o"];
  if ("visibilityState" in document) {
    return "visibilityState";
  }
  for (var i = 0; i < prefixes.length; i++) {
    if (prefixes[i] + "VisibilityState" in document) {
      return prefixes[i] + "VisibilityState";
    }
  }
  return null;
};

if (getHiddenProp()) {
  var evtname = getHiddenProp().replace(/[H|h]idden/, "") + "visibilitychange";
  // 添加页面显示隐藏监听事件
  document.addEventListener(
    evtname,
    function() {
      let tempState = "show";
      if (document[getVisibilityState()] !== "visible") {
        tempState = "hide";
      } else {
        tempState = "show";
      }
      Bus.$emit("pageStateChange", {
        state: tempState
      });
    },
    false
  );
}
export default Bus;
